package com.ylbh.modules.activity.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ylbh.common.annotation.SysLog;
import com.ylbh.common.pojo.activity.dto.ActivityGoodsDTO;
import com.ylbh.common.pojo.activity.vo.ActivityGoodsSpecDataJson;
import com.ylbh.common.pojo.activity.vo.ActivitySpecJson;
import com.ylbh.common.pojo.activity.vo.ShoppingActivityGoodsVO;
import com.ylbh.common.pojo.activity.vo.WholePointActivitiesTimeVO;
import com.ylbh.common.utils.*;
import com.ylbh.modules.activity.service.ActivityGoodsService;
import com.ylbh.modules.activity.service.SpikeGoodsService;
import com.ylbh.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * 活动商品信息
 *
 * @author mgh
 * @date 2019-04-22 15:25:57
 */
@RestController
@RequestMapping("activity/spikeGoods")
public class SpikeGoodsController extends AbstractController {
    @Autowired
    private SpikeGoodsService spikeGoodsService;

    @Autowired
    private ActivityGoodsService activityGoodsService;

    @Autowired
    RedisUtils redisUtils;
    /**
     * 获取活动商品列表
     */
    @RequestMapping("/queryActivityGoodsList")
    @RequiresPermissions("spike:goods:queryActivityGoodsList")
    public CommonResult<PageUtils> list(@RequestParam Map<String, Object> params){
        PageUtils page = spikeGoodsService.queryActivityGoodsList(params);

        return Ref.ok(page);
    }


    /**
     * 通过id获取商品
     */
    @RequestMapping("/getActivityGoodsById/{id}")
    @RequiresPermissions("spike:goods:getActivityGoodsById")
    public CommonResult<ActivityGoodsDTO> info(@PathVariable("id") String id){
        ActivityGoodsDTO shoppingActivityGoods = spikeGoodsService.getById(id);

        return Ref.ok(shoppingActivityGoods);
    }

    /**
     * 新增
     */
    @SysLog("新增抢购商品")
    @RequestMapping("/add")
    @RequiresPermissions("spike:goods:add")
    public CommonResult save(@RequestBody ActivityGoodsDTO shoppingActivityGoods) {
        JSONObject jsonObject = JSON.parseObject(shoppingActivityGoods.getOptGoods());
        String activityId = shoppingActivityGoods.getActivityId();
//        String state = shoppingActivityGoods.getState();
        // 查询活动的状态
//        String state = spikeGoodsService.selectActivityState(shoppingActivityGoods.getId());
        for(String key: jsonObject.keySet()){
            JSONObject jsonObject1 = jsonObject.getJSONObject(key);
            // 查询商品详细信息
            shoppingActivityGoods = activityGoodsService.getActivityGoodsById(Integer.parseInt(key));
            shoppingActivityGoods.setGoodsId(key);
            shoppingActivityGoods.setActivityId(activityId);
            shoppingActivityGoods.setId(new IdWorker().nextId());
            String goodsImg = jsonObject1.getString("goodsImg");
            goodsImg = goodsImg.substring(goodsImg.indexOf("consumer")+9, goodsImg.length());
            shoppingActivityGoods.setGoodsImages(goodsImg);
            shoppingActivityGoods.setGoodsName(jsonObject1.getString("goodsName"));
            shoppingActivityGoods.setSendIntegral(jsonObject1.getInteger("goodsIntegral"));
            shoppingActivityGoods.setCreateTime(new Date());
            shoppingActivityGoods.setCreateUserId(getUserId().intValue());
            shoppingActivityGoods.setDeleteStatus(1);
            shoppingActivityGoods.setActivityGoodsInventoryDetail(jsonObject1.getString("activityGoodsInventoryDetail"));
            shoppingActivityGoods.setGoodsInputInventory(shoppingActivityGoods.getGoodsInventory());
            String specs = jsonObject1.getString("specs");
            // 前端json规格
            List<ActivitySpecJson> activitySpecJsons = FastJsonUtil.toList(specs, ActivitySpecJson.class);
            ArrayList<ActivityGoodsSpecDataJson> agsdjList = new ArrayList<>();
            for (ActivitySpecJson asj:activitySpecJsons) {
                ActivityGoodsSpecDataJson agsdj = new ActivityGoodsSpecDataJson();
                BeanUtils.copyProperties(asj, agsdj);
                agsdj.setIntegral(asj.getActivityIntegral());
                agsdjList.add(agsdj);
            }
            JSONArray objects = new JSONArray(agsdjList);
            shoppingActivityGoods.setGoodsInventoryDetail(objects.toString());

//            if("1".equals(shoppingActivityGoods.getPriceType())){
//                shoppingActivityGoods.setGoodsIntegral(jsonObject1.getInteger("minPrice"));
//            }else if("2".equals(shoppingActivityGoods.getPriceType())){
//                shoppingActivityGoods.setVipPrice(new BigDecimal(jsonObject1.getFloat("minPrice")));
//                shoppingActivityGoods.setGoodsCostingPrice(new BigDecimal(jsonObject1.getFloat("goodsCostingPrice")));
//                shoppingActivityGoods.setGoodsIntegral(jsonObject1.getInteger("goodsIntegral"));
//            }
            shoppingActivityGoods.setGoodsPrice(new BigDecimal(jsonObject1.getFloat("goodsPrice")));
            shoppingActivityGoods.setVipPrice(new BigDecimal(jsonObject1.getFloat("minPrice")));
            shoppingActivityGoods.setGoodsCostingPrice(new BigDecimal(jsonObject1.getFloat("goodsCostingPrice")));
            shoppingActivityGoods.setGoodsIntegral(jsonObject1.getInteger("sendIntegral"));

            if (null != jsonObject1.getFloat("activityPrice"))
                shoppingActivityGoods.setVipPrice(new BigDecimal(jsonObject1.getFloat("activityPrice")));
            Integer sequence = spikeGoodsService.getLastSequence(shoppingActivityGoods.getActivityId());
            shoppingActivityGoods.setGoodsSequence(sequence + 1);
            shoppingActivityGoods.setState("1");
            spikeGoodsService.save(shoppingActivityGoods);
            // 查询出整点分场的开始时间和结束时间
            WholePointActivitiesTimeVO time = spikeGoodsService.getActivityTime(shoppingActivityGoods.getActivityId());
            ShoppingActivityGoodsVO vo = spikeGoodsService.copyData(shoppingActivityGoods);
            vo.setBeginTime(time.getBeginTime().getTime());
            vo.setEndTime(time.getEndTime().getTime());
            vo.setGoodsInputInventory(shoppingActivityGoods.getGoodsInventory());
            vo.setGoodsSaleNum("0");
            redisUtils.set("seckillGoods" + shoppingActivityGoods.getGoodsId(), vo);
            Long invalidTime = spikeGoodsService.addRedisInvalidTime(new Date(), time.getEndTime());
            // 添加redis失效时间
            redisUtils.expire("seckillGoods" + shoppingActivityGoods.getGoodsId(), invalidTime, TimeUnit.SECONDS);
        }
        return Ref.ok();
    }

    /**
     * 修改
     */
    @SysLog("修改抢购商品")
    @RequestMapping("/modify")
    @RequiresPermissions("spike:goods:modify")
    public CommonResult update(@RequestBody ActivityGoodsDTO shoppingActivityGoods){
        // 删除秒杀缓存
        redisUtils.deleteKeys("querySeckillGoodsInfoByPage*");
        redisUtils.deleteKeys("com.yilianbaihui.shopping.seckill*");
        //
        ActivityGoodsDTO dto = spikeGoodsService.selectActivityGoods(shoppingActivityGoods.getId());
        shoppingActivityGoods.setUpdateUserId(getUserId().intValue());
        if("1".equals(shoppingActivityGoods.getPriceType())){
            shoppingActivityGoods.setGoodsIntegral(shoppingActivityGoods.getMinPrice().intValue());
        }else if("2".equals(shoppingActivityGoods.getPriceType())){
            shoppingActivityGoods.setVipPrice(shoppingActivityGoods.getMinPrice());
        }
        shoppingActivityGoods.setGoodsInputInventory(shoppingActivityGoods.getGoodsInventory());
		spikeGoodsService.updateById(shoppingActivityGoods);
        // 查询出整点分场的开始时间和结束时间
        WholePointActivitiesTimeVO time = spikeGoodsService.getActivityTimeById(shoppingActivityGoods.getId());
        ShoppingActivityGoodsVO vo = spikeGoodsService.copyData(shoppingActivityGoods);
        vo.setVipPrice(shoppingActivityGoods.getMinPrice());
        vo.setGoodsPrice(shoppingActivityGoods.getGoodsPrice());
        vo.setGoodsIntegral(shoppingActivityGoods.getGoodsIntegral());
        vo.setGoodsInventory(shoppingActivityGoods.getGoodsInventory());
        vo.setGoodsInputInventory(shoppingActivityGoods.getGoodsInventory());
        vo.setBeginTime(time.getBeginTime().getTime());
        vo.setEndTime(time.getEndTime().getTime());
        vo.setGoodsId(dto.getGoodsId());
//        vo.setGoodsPrice(dto.getGoodsPrice());
//        vo.setGoodsSaleNum(dto.getGoodsSaleNum().toString());
        vo.setExpressTransFee(dto.getExpressTransFee());
        vo.setActivityId(dto.getActivityId());
        redisUtils.set("seckillGoods" + time.getId(), vo);
        Long invalidTime = spikeGoodsService.addRedisInvalidTime(new Date(), time.getEndTime());
        // 添加redis失效时间
        redisUtils.expire("seckillGoods" + time.getId(), invalidTime, TimeUnit.SECONDS);
        return Ref.ok();
    }

    /**
     * 删除
     */
    @SysLog("删除抢购商品")
    @RequestMapping("/remove")
    @RequiresPermissions("spike:goods:remove")
    public CommonResult delete(@RequestBody String[] ids){
        // 删除秒杀缓存
        redisUtils.deleteKeys("querySeckillGoodsInfoByPage*");
        redisUtils.deleteKeys("com.yilianbaihui.shopping.seckill*");
        ActivityGoodsDTO activityGoodsDTO = new ActivityGoodsDTO();
        activityGoodsDTO.setDeleteStatus(0);
        for (String id:ids) {
            activityGoodsDTO.setId(id);
            spikeGoodsService.updateById(activityGoodsDTO);
        }

        return Ref.ok();
    }
}
